import React, { useEffect } from 'react'
import { Routes, Route, Navigate, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import Home from './pages/WSC/Home'
import Lgoin from './pages/LXT/Lgoin'
// 李伊帆
import Logins from './pages/LYF/qian/Logins'
import Houtai from './pages/LYF/hou/Houtai'
import Coursess from './pages/LYF/qian/Coursess'
import Book from './pages/LYF/qian/Book'
import CourseDetail from './pages/LYF/qian/CourseDetail'
import PaymentSuccess from './pages/LYF/qian/PaymentSuccess'

import Zhuce from './pages/LXT/zhuce'
import Chongzhi from './pages/LXT/Chongzhi'
import LoginSuccess from './pages/LXT/LoginSuccess'
import RegisterSuccess from './pages/LXT/RegisterSuccess'
import LoginError from './pages/LXT/LoginError'
import TestAPI from './pages/LXT/TestAPI'
import ProtectedRoute from './components/ProtectedRoute'
// 张鹏飞
import ChatAi from './pages/ZPF/DifyAi/ChatAi'
import ZhiboHome from "./pages/ZPF/WebRTC/zhibo-home";
import ZhiboStreamer from "./pages/ZPF/WebRTC/zhibo-streamer";
import ZhiboViewer from "./pages/ZPF/WebRTC/zhibo-viewer";
import Angil from './pages/ZPF/Angil'
import Homed from './pages/ZPF/DifyAi/Homed'
// 王舒畅
import ZhiBoHome from "./pages/WSC/WebRTC/Zhu";
import LiaoA from "./pages/WSC/WebRTC/Liao-A";
import LiaoB from "./pages/WSC/WebRTC/Liao-B";
import Tale from "./pages/WSC/Tale"
import Xue from './pages/WSC/Xue'


import GlobalI18nTest from './components/GlobalI18nTest'
import ButtonContrastTest from './components/ButtonContrastTest'
import LoginTest from './components/LoginTest'
import PositionTest from './components/PositionTest'
import LoginFixTest from './components/LoginFixTest'


import axios from 'axios'
export default function App() {
  const token = localStorage.getItem('token')
  const navigate = useNavigate()
  const { i18n } = useTranslation()

   // 监听语言变化，确保localStorage同步
   useEffect(() => {
    const handleLanguageChange = (lng) => {
      localStorage.setItem('language', lng);
      console.log('语言已切换为:', lng);
    };

    i18n.on('languageChanged', handleLanguageChange);

    return () => {
      i18n.off('languageChanged', handleLanguageChange);
    };
  }, [i18n]);

  // 全局设置axios默认headers
  useEffect(() => {
    // 为每个请求自动添加token
    axios.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('token');
        if (token) {
          // 判断token是否已经包含"Bearer "前缀
          const tokenValue = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
          config.headers['Authorization'] = tokenValue;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 处理响应错误，如401未授权
    axios.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response && error.response.status === 401) {
          // 未授权，可能是token过期
          localStorage.removeItem('token');
          navigate('/login');
        }
        return Promise.reject(error);
      }
    );
  }, [navigate]);

  // 全局检查token过期情况
  useEffect(() => {
    // 检查token是否过期的函数
    const checkTokenExpiration = () => {
      const token = localStorage.getItem('token');

      if (token) {
        try {
          // 获取实际的JWT部分（如果token带有Bearer前缀）
          const tokenParts = token.split(' ');
          const jwt = tokenParts.length > 1 ? tokenParts[1] : token;

          // JWT token解析逻辑来检查过期时间
          // JWT格式: header.payload.signature
          const payload = JSON.parse(atob(jwt.split('.')[1]));

          // 如果payload中有exp字段，表示过期时间戳
          if (payload && payload.exp) {
            // exp是秒级时间戳，需要转换为毫秒
            const expTime = payload.exp * 1000;
            const currentTime = Date.now();

            // 如果token已过期
            if (expTime <= currentTime) {
              console.log('Token已过期');
              localStorage.removeItem('token');
              navigate('/login');
              return;
            }

            // 如果token即将过期（比如30分钟内）
            const thirtyMinutes = 30 * 60 * 1000; // 30分钟，毫秒
            if (expTime - currentTime <= thirtyMinutes) {
              console.log('Token即将过期，可以在这里实现自动刷新token的逻辑');
              // 可以在这里添加刷新token的逻辑
            }
          }
        } catch (error) {
          // token格式错误
          console.error('Token解析失败:', error);
          localStorage.removeItem('token');
          navigate('/login');
        }
      }
    };

    // 初始检查
    checkTokenExpiration();

    // 设置定期检查（每分钟检查一次）
    const interval = setInterval(checkTokenExpiration, 60 * 1000);

    return () => clearInterval(interval);
  }, [navigate]);

  return (
    <div>
      <Routes>
        {/* 公开路由 */}
        <Route path='/login' element={<Lgoin />} />
        <Route path='/zhuce' element={<Zhuce />} />
        <Route path='/reset-password' element={<Chongzhi />} />
        <Route path='/forgot-password' element={<Navigate to="/reset-password" replace />} />
        <Route path='/login-success' element={<LoginSuccess />} />
        <Route path='/register-success' element={<RegisterSuccess />} />
        <Route path='/login-error' element={<LoginError />} />
        <Route path='/test-api' element={<TestAPI />} />
        

        {/* 需要验证的路由 */}
        <Route path='/' element={<Home />} />
        <Route path='/' element={
          <ProtectedRoute>
            <Navigate to="/home" replace />
           </ProtectedRoute>
        } />

        {/* 未匹配的路由重定向到登录页 */}
        {/* <Route path='*' element={<Navigate to="/login" replace />} /> */}
        {/* 李伊帆 */}
        <Route path='/logins' element={<Logins />} />
        <Route path='/houtai' element={<Houtai />} />
        <Route path='/coursess' element={<Coursess />} />
        <Route path='/course-detail/:courseId' element={<CourseDetail />} />
        <Route path='/books' element={<Book />} />
        <Route path='/payment-success' element={<PaymentSuccess />} />
        
        <Route path='/xue' element={<Xue />} />
        <Route path='/chatAi' element={<ChatAi />} />
        <Route path='/zhibohome' element={<ZhiboHome />} />
        <Route path='/zhibo-streamer' element={<ZhiboStreamer />} />
        <Route path='/zhibo-viewer' element={<ZhiboViewer />} />
        <Route path='/homed' element={<Homed />} />
        {/* WebRTC 聊天室路由 */}
        <Route path='/chatroom' element={<ZhiBoHome />} />
        <Route path='/chatroom/sender' element={<LiaoA />} />
        <Route path='/chatroom/receiver' element={<LiaoB />} />
        <Route path='/tale' element={<Tale />} />
        <Route path='/angil' element={<Angil />} />

          {/* 国际化测试页面 */}
          <Route path='/i18n-test' element={<GlobalI18nTest />} />
        <Route path='/button-test' element={<ButtonContrastTest />} />
        <Route path='/login-test' element={<LoginTest />} />
        <Route path='/position-test' element={<PositionTest />} />
        <Route path='/login-fix-test' element={<LoginFixTest />} />
      </Routes>
    </div>
  )
}
